# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:

import os
from untils.MysqlTools import MysqlTools
import hashlib

class Tools1:
    '''提取出所有subgroup图片'''
    def __init__(self, brand, db_config, strucTb):
        self.brand = brand
        self.strucTb = strucTb
        self.sqlDb = MysqlTools(db_config=db_config, type='dict')
        self.imgPath = os.getcwd()+os.sep+'..'+os.sep+'PNG'+os.sep+brand
        self.destPath = os.getcwd()+os.sep+'..'+os.sep+'sub'+os.sep+brand
        if not os.path.exists(self.destPath):
            os.makedirs(self.destPath)


    def _get_md5(self, b):
        '''获取md5加密电子指纹'''
        _md5 = hashlib.md5()
        _md5.update(b)
        return _md5.hexdigest()

    def get_cid_subgroup(self):
        sql = 'select distinct cid, subgroup from `{}`'.format(self.strucTb)
        data = self.sqlDb.select_all(sql)
        return data

    def run(self):
        cid_sub = self.get_cid_subgroup()
        _set = set()
        for cs in cid_sub:
            cid = cs.get("cid")
            subgroup = cs.get("subgroup")
            srcPath = self.imgPath+os.sep+cid+os.sep+subgroup+'.png'
            if not os.path.exists(srcPath):
                continue
            b = open(srcPath, 'rb').read()

            _md5 = self._get_md5(b)
            if _md5 in _set:
                continue
            _set.add(_md5)
            destPath = self.destPath+os.sep+subgroup+'.png'
            if not os.path.exists(destPath):
                command = 'cp "{}" "{}"'.format(srcPath, destPath)
                print(command)
                os.system(command)

def main():
    brand = 'citroen'
    db_config = dict(
        host="192.168.10.166",
        port=3306,
        user="a",
        passwd="110",
        db=brand,
        charset="utf8",
    )
    strucTb = 'cars_structure_collection'
    tools = Tools1(brand, db_config, strucTb)
    tools.run()

if __name__ == '__main__':
    main()
